<?php

namespace app\helps;

include_once APP_EXTEND . 'aliyun/autoload.php';

use OSS\OssClient;
use OSS\Core\OssException;
use think\Facade\Env;
use think\File;
use think\Db;
class Aliyun
{
    protected $regionId = '';
    protected $accessKeyId = '';
    protected $accessSecret = '';
    protected $roleArn = '';
    protected $bucket = '';
    protected $endpoint = '';
    protected $storage = null;
    protected $uploadType = 'ram';

    public function __construct($regionId = '', $accessKeyId = '', $accessSecret = '', $rolaArn = '', $bucket = '', $endpoint = '')
    {
        $this->regionId = $regionId ?: Env::get('oss.regionId');
        $this->accessKeyId = $accessKeyId ?: Env::get('oss.accessKeyId');
        $this->accessSecret = $accessSecret ?: Env::get('oss.accessSecret');
        $this->roleArn = $rolaArn ?: Env::get('oss.roleArn');
        $this->bucket = $bucket ?: Env::get('oss.bucket');
        $this->endpoint = $endpoint ?: Env::get('oss.endpoint');
        $this->size     = Env::get('cos.size'); //上传文件大小限制
    }

    /**
     * 阿里云oss文件上传
     * OSS上传方式
     * ram：使用ram账号的key和secret直接上传（适用于服务器上传文件）
     * sts: 适用ram账号生成临时的sts的的key和secret直接上传（适用于APP上传文件）
     */
    public function upload_alioss($file, $uid = '',$folder = '')
    {
        $info = $file->getInfo();
        $hash = $file->hash();
        $name = explode('.',$info['name']);
        $nameSize =count($name);
        $newname = $this->changeName($hash,$info['name']);
        //判断文件上传是否符合要求
        if($info['size'] > $this->size){
            return ['status'=>0,'msg'=>'文件过大'];false;
        }
        $ext = array('jpg','png','gif');
        if(!in_array($name[$nameSize-1],$ext)){
            return ['status'=>0,'msg'=>'文件类型错误'];false;
        }

        try {
            if ($this->uploadType == 'ram') {
                $ossClient = new OssClient($this->accessKeyId, $this->accessSecret, $this->endpoint);
            } else {
                $ossClient = new OssClient($this->accessKeyId, $this->accessSecret, $this->endpoint, false);
            }
        } catch (OssException $e) {
            return ['status'=>0,'msg'=>'构建异常'.$e->getMessage()];false;
        }
        if ($folder) {
            $newname = str_replace('//', '/', $folder . '/' . $newname);
        }
        $options = array();
        $options['ContentType']='image/jpg';
        $options['ContentDisposition']='inline';
        try {
            $res = $ossClient->uploadFile($this->bucket, $newname, $info['tmp_name'],$options);
            //检查本地数据库是否有该文件，根据文件hash判断
            $check = Db::table('tb_file')->where('hash',$hash)->find();
            if($check){
                $check['save_name'] = $check['file_name'];
                return ['status' => 1, 'msg' => '文件已存在,已返回ID','data'=> $check,'pic'=>$check['id']];die;
            }
            //存本地数据库
            $arr = array();
            $arr['extension'] = $this->fileExt($info['name']);;
            $arr['save_name'] = $newname;
            $arr['file_name'] = $res['info']['url'];
            $arr['hash'] = $hash;
            $arr['type'] = 2;
            $arr['uid'] = $uid?$uid:0;
            $arr['time'] = time();
            $insert = Db::table('tb_file')->insertGetId($arr);
            if($insert){
                $arr['save_name'] = $res['info']['url'];
                return ['status' => 1, 'msg' => '图片上传成功','data'=> $arr,'pic'=>$insert];
            }else{
                return ['status' => 0, 'msg' => '入库失败'];
            }
        } catch (OssException $e) {
            return ['status'=>0,'msg'=>'上传异常'.$e->getMessage()];false;
        }

        return false;
    }


    public function uploadString($string, $name, $folder = '')
    {
        $config = $this->getCredentials();
        if (!$config) {
            return false;
        }

        $newname = $this->changeName($name);
        if ($folder) {
            $newname = str_replace('//', '/', $folder . '/' . $newname);
        }

        try {
            if ($this->uploadType == 'ram') {
                $ossClient = new OssClient($config['AccessKeyId'], $config['AccessKeySecret'], $this->endpoint);
            } else {
                $ossClient = new OssClient($config['AccessKeyId'], $config['AccessKeySecret'], $this->endpoint, false, $config['SecurityToken']);
            }
        } catch (OssException $e) {
            return false;
        }

        try {
            $res = $ossClient->putObject($this->bucket, $newname, $string);
            return $res['info']['url'];
        } catch (OssException $e) {
            return false;
        }
    }

    public function changeName($hash,$fileName)
    {
        //$name = md5(uniqid(rand()));
        $ext = $this->fileExt($fileName);
        return $hash . '.' . $ext;
    }

    public function fileExt($fileName)
    {
        $tmp = explode(".", $fileName);
        $fileExt = $tmp[count($tmp) - 1];
        return strtolower($fileExt);
    }
}

